<?php

namespace app\controllers\admin\uni\finance;

use app\controllers\admin\base\AdminController;
use app\models\user\User;
use app\models\user\UserCommission as Model;

class ProfitController extends AdminController
{
    public function actionList()
    {
        $user_id = $this->post('user_id');
        $export = $this->post('export');

        $month = $this->post('month', date('Y-m-d'));

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            // ->where(['type' => 10])
            ->where(['status' => 10]);

        // $query = (new \yii\db\Query())
        //     ->select('sum(balance) as sum, user_id')
        //     ->from('user_commission')
        //     ->where('status = 10')
        //     ->groupBy(['user_id'])
        //     ->limit(2)
        //     ->all();
        // var_dump($query);exit;

        // if ($sort) {
        //     $prop = substr($sort, 0, 1);
        //     $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
        //     $order = substr($sort, 1);
        //     $query->orderBy([$order => $prop]);
        // } else {
        //     $query->orderBy(['id' => SORT_DESC]);
        // }

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        if ($month) {
            $query->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m', strtotime($month))]);
        }

        $query->select('sum(balance) as sum, user_id')
            ->groupBy(['user_id']);

        // export
        if ($export) {
            $e = $query->asArray()->all();
            foreach ($e as &$item) {
                $item['user'] = User::findOne(['id' => $item['user_id']]);
                if ($item['user']['nickname']) {
                    $item['user']['nickname'] = base64_decode($item['user']['nickname']);
                }
                $item['month'] = $month;
            }
            return $this->success($e);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with('user')
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $item['user'] = User::findOne(['id' => $item['user_id']]);
            if ($item['user']['nickname']) {
                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
            }
            $item['month'] = $month;
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }
}